//User模块的小仓库
import {
  reqGetCode,
  reqUserLogin,
  reqUserRegister,
  reqUserInfo,
  reqLogout
} from '@/api'
// actions 处理异步，接受服务器端的数据
const actions = {
  // 验证码接口  验证码返回了，但是正常情况是把验证码发在用户手机上
  async getCode(context, phone) {
    let result = await reqGetCode(phone)
    if (result.code == 200) {
      context.commit('GETCODE', result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 用户注册
  async userRegister(context, data) {
    let result = await reqUserRegister(data)
    if (result.code == 200) {
      context.commit('GETCODE', result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 用户登录getUserInfo
  async userLogin(context, data) {
    let result = await reqUserLogin(data)
    if (result.code == 200) {
      // 服务器下发token  
      context.commit('USERLOGIN', result.data.token)
      // 持久化存储token
      localStorage.setItem("TOKEN",result.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 获取用户信息
  async getUserInfo(context,value){
    let result = await reqUserInfo()
    if (result.code == 200) {
      // 服务器下发token  
      context.commit('GETUSERINFO', result.data)
    }
  },
  // 用户退出登录
  async userLogout(context, value){
    let result =await reqLogout()
    if (result.code == 200) {
      // 服务器下发token  
      context.commit('CLEAR')
      return 'ok'
    }else{
      return Promise.reject(new Error('faile'))
    }
  }
}
//mutations 修改state的唯一方法
const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  USERLOGIN(state, token) {
    state.token = token
  },
  GETUSERINFO(state,userInfo){
    state.userInfo = userInfo
  },
  CLEAR(state){
    state.token =''
    state.userInfo = {}
    localStorage.removeItem("TOKEN")
  }
}
//state仓库存储数据
const state = {
  code: '',
  token:localStorage.getItem("TOKEN"),
  userInfo:{}
}
// getters 计算属性，组件获取仓库的数据更加方便
const getters = {}
export default {
  state,
  actions,
  mutations,
  getters,
};